package edu.maimonides.ejercicios.ides2.sql.dao.hsql;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import edu.maimonides.ejercicios.ides2.sql.dao.PersonaDAO;
import edu.maimonides.ejercicios.ides2.sql.ddl.hsql.JDBCUtils;
import edu.maimonides.ejercicios.ides2.sql.model.Persona;

public class PersonaDaoHSQL implements PersonaDAO {

	private Connection connection;
	
	public PersonaDaoHSQL(Connection connection) {
		super();
		this.connection = connection;
	}

	public void create(Persona persona) throws SQLException {
		int count = JDBCUtils.executeStatement(String.format("INSERT INTO PERSONAS VALUES ('%1s','%2s','%3s')", persona.getDni(),persona.getNombre(), persona.getApellido()), getConnection());
		if(count==0){
			throw new SQLException("Didn´t create " + persona);
		}
	}

	public void delete(Persona persona) throws SQLException {
		int count = JDBCUtils.executeStatement(String.format("DELETE FROM PERSONAS WHERE DNI='%1s'", persona.getDni()), getConnection());
		if(count==0){
			throw new SQLException("Persona doesn't exist " + persona);
		}
	}

	public void update(Persona persona) throws SQLException {
		int count= JDBCUtils.executeStatement(String.format("UPDATE PERSONAS SET NOMBRE='%1s', APELLIDO='%2s' WHERE DNI='%3s'", persona.getNombre(),persona.getApellido(),persona.getDni()), getConnection());
		if(count==0){
			throw new SQLException("Persona doesn't exist " + persona);
		}
	}

	public List<Persona> getByCondition(String condition) throws SQLException {
		return JDBCUtils.executeQuery(String.format("SELECT * FROM PERSONAS WHERE '%1s'", condition), getConnection(), new PersonaFactory());
	}

	public List<Persona> all() throws SQLException {
		return JDBCUtils.executeQuery(String.format("SELECT * FROM PERSONAS"), getConnection(), new PersonaFactory());

	}

	public Connection getConnection() {
		return connection;
	}

	public void setConnection(Connection connection) {
		this.connection = connection;
	}

}
